const { contextBridge, ipcRenderer } = require('electron');
const { marked } = require('marked');
const { markedHighlight } = require('marked-highlight');
const hljs = require('highlight.js');

console.log('Preload script loaded');

// 配置marked
marked.setOptions({
  gfm: true,
  breaks: true
});

marked.use(markedHighlight({
  langPrefix: 'hljs language-',
  highlight(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  }
}));

contextBridge.exposeInMainWorld('electronAPI', {
  send: (channel, data) => ipcRenderer.send(channel, data),
  on: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args)),
  marked: {
    parse: (text) => {
      try {
        console.log('渲染Markdown内容长度:', text.length);
        const result = marked.parse(text);
        return result;
      } catch (error) {
        console.error('Markdown渲染错误:', error);
        return `<p>渲染错误: ${error.message}</p>`;
      }
    }
  },
  createFile: (filename, content) => ipcRenderer.invoke('create-file', filename, content),
  deleteFile: (filePath) => ipcRenderer.invoke('delete-file', filePath),
  getConfigPath: () => ipcRenderer.invoke('get-config-path'),
  readDirectory: (dirPath) => ipcRenderer.invoke('read-directory', dirPath),
  readFileFirstLine: (filePath) => ipcRenderer.invoke('read-file-first-line', filePath),
  readFile: (filePath) => ipcRenderer.invoke('read-file', filePath),
  saveFile: (filePath, content) => ipcRenderer.invoke('save-file', filePath, content),
  getFileStats: (filePath) => ipcRenderer.invoke('get-file-stats', filePath),
  selectFolder: () => ipcRenderer.invoke('select-folder'),
  config: {
    get: (key) => ipcRenderer.invoke('config-get', key),
    update: (updates) => ipcRenderer.invoke('config-update', updates),
    reset: () => ipcRenderer.invoke('config-reset')
  }
});